package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 这个类是SpringMVC框架与 Tomcat 容器整合的一个的关键类,接管了处理请求的工作.
 * 这样,当Tomcat 将请求对象和响应对象创建完毕后在粗粒请求的缓解通过调用这个类来完成,
 * 从而将处理请求交给了 SpringMVC 框架
 * 并在处理后发送响应给浏览器
 */
public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File rootDir;
    private static File staticDir;

    static {
        try {
            rootDir = new File(ClientHandler.class.getClassLoader()
                    .getResource(".").toURI());
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e ) {
            e.printStackTrace();
        }
    }
    private DispatcherServlet () { }

    public static DispatcherServlet getInstance() {
        return instance;
    }
    public void service (HttpServletRequest request , HttpServletResponse response) {
        String path = request.getUri();
        File file = new File(staticDir,path);

        if (file.isFile()) {
            response.setContentFile(file);
        } else {
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File(staticDir,"/root/404.html");
            response.setContentFile(file);
        }

    }
}
